package com.apobates.forum.grief.function;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * 取代If/Else命令式表示式
 * 示例:
 * boolean result = EitherResult
 *          .<Boolean>of(form.getId()>0)
 *          .thenIf(() -> notePageService.edit(form.getId(), form))
 *          .orElse(() -> notePageService.create(form.getTitle(), form.getContent(), form.isQuality(), form.getMarkPath(), form.getRanking()).isPresent())
 *          .get()
 *          .orElse(false);
 * @author xiaofanku
 * @since 20210123
 * @param <T> 返回值类型
 */
public final class EitherResult<T> {
    private final boolean condition;
    private final Optional<T> result;

    private EitherResult(boolean condition, Optional<T> result) {
        this.condition = condition;
        this.result = result;
    }

    /**
     * 设置条件表达式
     * @param whereExp 条件表达式
     * @param <T>
     * @return
     */
    public static <T> EitherResult<T> of(boolean whereExp){
        return new EitherResult<>(whereExp, Optional.empty());
    }

    /**
     * 条件表达式为True时执行参数结果
     * @param trueFunctionExp if的执行函数
     * @return
     */
    public EitherResult<T> thenIf(Supplier<T> trueFunctionExp) {
        if(condition) {
            Optional<T> trueRs = Optional.ofNullable(trueFunctionExp.get());
            return new EitherResult<>(condition, trueRs);
        }
        return this;
    }

    /**
     * 条件表达式为False时执行参数结果
     * @param falseFunctionExp else的执行函数
     * @return
     */
    public EitherResult<T> orElse(Supplier<T> falseFunctionExp){
        if(!condition) {
            Optional<T> falseRs = Optional.ofNullable(falseFunctionExp.get());
            return new EitherResult<>(condition, falseRs);
        }
        return this;
    }

    /**
     * 获取最终的结果
     * @return
     */
    public Optional<T> get(){
        return this.result;
    }
}
